package com.hflyeer.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hflyeer.dto.StudentEx;
import com.hflyeer.entity.College;
import com.hflyeer.entity.Grade;
import com.hflyeer.entity.Student;
import com.hflyeer.exception.StudentException;
import com.hflyeer.mapper.CollegeMapper;
import com.hflyeer.mapper.GradeMapper;
import com.hflyeer.mapper.StudentMapper;
import com.hflyeer.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 学生 服务实现类
 * </p>
 *
 * @author hflyeer
 * @since 2021-06-01
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Resource
    private StudentMapper studentDao;
    @Resource
    private CollegeMapper collegeDao;
    @Resource
    private GradeMapper gradeDao;

    @Override
    @Transactional
    public int addStudent(StudentEx stu) {

        College college = new College();
        college.setCollegeName(stu.getCollegeName());
        int insert_college = collegeDao.insert(college);
        if(insert_college>0){
            // 将添加到数据库中学院id回添到stu对象中
            stu.setCollegeId(college.getId());
        }else{
            throw new StudentException("学院以存在");
        }
        Grade grade = new Grade();
        grade.setGradeName(stu.getGradeName());
        int insert_grade = gradeDao.insert(grade);
        if (insert_college>0){
            stu.setGradeId(grade.getId());
        }else{
            throw new StudentException("班级以存在`");
        }

        int insert = studentDao.insert(stu);
        if (insert<=0){
            throw new StudentException("添加失败");
        }

        return stu.getId();
    }

    @Override
    @Transactional
    public int updateScore(Student stu) {
        UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();
        studentUpdateWrapper.eq("id", stu.getId()).set("score", stu.getScore()).set("create_time",new Date());
        return studentDao.update(null,studentUpdateWrapper);
    }
}
